package hu.jonas.allunit.model;

import hu.jonas.allunit.views.ProgressPanel;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Display;

public class TestResultModel {

	private List<TestResult> listOfTestResults = new ArrayList<TestResult>(); 
	private Viewer viewer;
	private ProgressPanel progressPanel;
	
	private int totalTestCount;
	private int completedTestCount;
	private int failedTestCount;
	
	public TestResult[] getTestResults() {
		return listOfTestResults.toArray(new TestResult[0]);
	}

	public void add(TestResult testResult) {
		listOfTestResults.add(testResult);
		completedTestCount = listOfTestResults.size();
		if (!TestResultOutcome.isSuccessful(testResult.getOutcome())) {
			failedTestCount++;
		}
		notifyViews();
	}

	public void clear() {
		listOfTestResults.clear();
		completedTestCount = 0;
		failedTestCount = 0;
		notifyViews();
	}
	
	public void setTotalTestCount(int totalTestCount) {
		this.totalTestCount = totalTestCount;
		Display.getDefault().syncExec(new Runnable() {
			
			@Override
			public void run() {
				progressPanel.setMaximum(TestResultModel.this.totalTestCount);
			}
		});
	}

	public ProgressPanel getProgressPanel() {
		return progressPanel;
	}

	public void setProgressPanel(ProgressPanel progressPanel) {
		this.progressPanel = progressPanel;
	}

	public Viewer getViewer() {
		return viewer;
	}

	public void setViewer(Viewer viewer) {
		this.viewer = viewer;
	}
	
	protected void notifyViews() {
		Display.getDefault().syncExec(new Runnable() {

			@Override
			public void run() {
				viewer.setInput(TestResultModel.this);
				viewer.refresh();
				progressPanel.setState(completedTestCount, failedTestCount != 0);
			}
		});
	}
	
}
